package edu.njust.underwater.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        LoginInterceptor loginInterceptor = new LoginInterceptor();

        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**");
    }

    /**
     * 设置静态资源映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations("classpath:/templates/img/");

        registry.addResourceHandler("/js/**")
                .addResourceLocations("classpath:/templates/js/");

        registry.addResourceHandler("/css/**")
                .addResourceLocations("classpath:/templates/css/");

        registry.addResourceHandler("/articles/**")
                .addResourceLocations("classpath:/templates/articles/");

        registry.addResourceHandler("/*.html")
                .addResourceLocations("classpath:/templates/");
    }


    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")  // 允许所有请求url
                .allowedOriginPatterns("*")        // 允许请求的进程
                .allowedHeaders("*")    // 允许所有请求头
                .allowedMethods("*")   // 允许的请求方法
                .allowCredentials(true)     // 允许携带cookie
                .maxAge(3600);  // 跨域验证的有效期：一个小时
    }

}
